package org.herrdommel.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.RelativeLayout;

/** Extends a relative layout to provide a checkable behaviour */
public class CheckableRelativeLayout extends RelativeLayout implements Checkable {

	public CheckableRelativeLayout(final Context context, final AttributeSet attrs, final int defStyle) {
		super(context, attrs, defStyle);
	}

	public CheckableRelativeLayout(final Context context, final AttributeSet attrs) {
		super(context, attrs);
	}

	public CheckableRelativeLayout(final Context context) {
		super(context);
	}

	private CheckBox checkBox;

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();

		// find checked text view
		final int childCount = getChildCount();
		for (int i = 0; i < childCount; ++i) {
			final View view = getChildAt(i);
			if (view instanceof CheckBox) {
				checkBox = (CheckBox) view;
				break;
			}
		}
	}

	@Override
	public boolean isChecked() {
		return checkBox != null ? checkBox.isChecked() : false;
	}

	@Override
	public void setChecked(final boolean checked) {
		if (checkBox != null) {
			checkBox.setChecked(checked);
		}
	}

	@Override
	public void toggle() {
		if (checkBox != null) {
			checkBox.toggle();
		}
	}

}
